// 用promise+ajax 封装axios插件

// ajax("url","get","数据",async,function(){
//   ajax("url","get","数据",async,function(){

//   })
// })
class Axios {
  constructor() {
    this.xhr = null
    try {
      this.xhr = new XMLHttpRequest()
    } catch (e) {
      this.xhr = new ActiveXObject('Microsoft.XML')
    }
  }

  // 序列化参数
  serialize(data) {
    //{name:1,age:2}===name=1&age=2
    if (!data) return ''
    var pairs = []
    for (var name in data) {
      if (!data.hasOwnProperty(name)) continue
      if (typeof data[name] === 'function') continue
      var value = data[name].toString()
      name = encodeURIComponent(name)
      value = encodeURIComponent(value)
      pairs.push(name + '=' + value)
    }
    return pairs.join('&')
  }

  //ajax封装
  $http({
    type = 'get',
    url = '',
    async = true,
    data = {},
    header = { 'Content-type': 'application/x-www-form-urlencoded' }
  }) {
    var xhr = this.xhr
    return new Promise((resolve, reject) => {
      // get 传参
      if (type == 'get') {
        url += '?' + this.serialize(data)
      }
      //2调用open
      xhr.open(type, url, async)
      // 3调用open
      if (type == 'post') {
        for (let x in header) {
          xhr.setRequestHeader(x, header[x])
        }
        xhr.send(this.serialize(data))
      } else {
        xhr.send()
      }
      //4等待数据返回
      xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
          resolve(JSON.parse(xhr.responseText)) //成功的数据用promise的resolve返回
        }
        if (xhr.status != 200) {
          //   //失败的数据用promise的reject返回
          reject(new Error({ status: xhr.status, tips: '数据调用错误' }))
        }
      }
    })
  }
}

export default new Axios()
